<template>
	<div class="register-container" v-loading="registering || loadingRoles || sendingMessage">

		<!-- 注册表单容器 -->
		<el-form ref="registerFormRef" :model="form" :rules="rules" @submit.prevent="handleRegister">
			<!-- 手机号输入框 -->
			<el-form-item prop="phone">
				<el-input v-model="form.phone" placeholder="请输入手机号" class="custom-input">
					<template #prefix>
						<span class="input-icon">
							<el-icon>
								<Iphone />
							</el-icon>
						</span>
					</template>
				</el-input>
			</el-form-item>

			<!-- 密码输入框 -->
			<el-form-item prop="password">
				<el-input v-model="form.password" :type="showPassword ? 'text' : 'password'" placeholder="请输入密码"
					class="custom-input">
					<template #prefix>
						<span class="input-icon">
							<el-icon>
								<Lock />
							</el-icon>
						</span>
					</template>
					<template #suffix>
						<span class="eye-icon" @click="togglePassword">
							<el-icon v-if="showPassword">
								<View />
							</el-icon>
							<el-icon v-else>
								<Hide />
							</el-icon>
						</span>
					</template>
				</el-input>
			</el-form-item>

			<!-- 确认密码输入框 -->
			<el-form-item prop="confirmPassword">
				<el-input v-model="form.confirmPassword" :type="showConfirmPassword ? 'text' : 'password'"
					placeholder="请再次输入密码" class="custom-input">
					<template #prefix>
						<span class="input-icon">
							<el-icon>
								<Lock />
							</el-icon>
						</span>
					</template>
					<template #suffix>
						<span class="eye-icon" @click="toggleConfirmPassword">
							<el-icon v-if="showConfirmPassword">
								<View />
							</el-icon>
							<el-icon v-else>
								<Hide />
							</el-icon>
						</span>
					</template>
				</el-input>
			</el-form-item>

			<!-- 角色选择框 -->
			<el-form-item prop="roleId">
				<el-select v-model="form.roleId" placeholder="请选择角色" class="custom-select">
					<el-option v-for="role in roles" :key="role.id" :label="role.roleName" :value="role.id" />
				</el-select>
			</el-form-item>

			<!-- 提交按钮 -->
			<div v-if="!registerSuccess">
				<el-button type="primary" native-type="submit" class="register-btn">
					注册
				</el-button>
			</div>

			<!-- 注册成功后的操作区域 -->
			<div v-else class="success-actions">
				<el-button type="success" @click="sendWelcomeMessage" class="send-message-btn">
					<el-icon>
						<Message />
					</el-icon>
					<span>向此员工发送信息</span>
				</el-button>
			</div>
		</el-form>
	</div>
</template>

<script>
	export default {
		name: 'PermissionView',
	};
</script>

<script setup>
	import {
		register
	} from '@/api/userManager'
	import {
		getRole
	} from '@/api/role'
	import {
		ElMessage
	} from 'element-plus';
	import {
		ref,
		reactive,
		onMounted
	} from 'vue';
	import {
		Iphone,
		View,
		Hide,
		Lock,
		Message
	} from '@element-plus/icons-vue'
	import {
		useRouter
	} from 'vue-router';

	const router = useRouter();

	/**
	 * 表单数据
	 */
	const form = reactive({
		phone: '',
		password: '',
		confirmPassword: '',
		roleId: ''
	})

	// 响应式数据
	const showPassword = ref(false)
	const showConfirmPassword = ref(false)
	const registering = ref(false)
	const loadingRoles = ref(false)
	const sendingMessage = ref(false)
	const registerSuccess = ref(false)
	const roles = ref([])
	const registerFormRef = ref(null)
	const registeredUserId = ref('') // 存储注册成功的用户ID

	/**
	 * 获取角色列表
	 */
	const fetchRoles = async () => {
		try {
			loadingRoles.value = true
			const res = await getRole()
			if (res.code === 200) {
				roles.value = res.data
			}
		} catch (error) {
			ElMessage.error('获取角色列表失败')
		} finally {
			loadingRoles.value = false
		}
	}

	onMounted(() => {
		fetchRoles()
	})

	/**
	 * 验证规则
	 */
	const validatePassword = (rule, value, callback) => {
		if (value !== form.password) {
			callback(new Error('两次输入的密码不一致'))
		} else {
			callback()
		}
	}

	const rules = reactive({
		phone: [{
				required: true,
				message: '请输入手机号',
				trigger: 'blur'
			},
			{
				pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
				message: '请输入有效的11位手机号',
				trigger: ['blur', 'change']
			}
		],
		password: [{
				required: true,
				message: '请输入密码',
				trigger: 'blur'
			},
			{
				min: 6,
				message: '密码长度不能少于6位',
				trigger: 'blur'
			}
		],
		confirmPassword: [{
				required: true,
				message: '请再次输入密码',
				trigger: 'blur'
			},
			{
				validator: validatePassword,
				trigger: ['blur', 'change']
			}
		],
		roleId: [{
			required: true,
			message: '请选择角色',
			trigger: 'change'
		}]
	})

	/**
	 * 切换密码显示
	 */
	const togglePassword = () => {
		showPassword.value = !showPassword.value
	}

	const toggleConfirmPassword = () => {
		showConfirmPassword.value = !showConfirmPassword.value
	}

	/**
	 * 注册处理
	 */
	const handleRegister = async () => {
		registering.value = true

		try {
			await registerFormRef.value.validate()
			const res = await register({
				phone: form.phone,
				password: form.password,
				roleId: form.roleId
			})

			if (res.code === 204) {
				registering.value = false
				registerSuccess.value = true
				ElMessage.success('注册成功')
			}
		} catch (error) {
			registering.value = false
			ElMessage.error(error.message || '注册失败')
		}
	}

	/**
	 * 发送欢迎信息
	 */
	const sendWelcomeMessage = async () => {
		try {
			sendingMessage.value = true
			// const res = await sendMessage({
			// 	userId: registeredUserId.value,
			// 	content: '欢迎加入我们的团队！请及时完善个人信息并设置密码。'
			// })

			// if (res.code === 200) {
			// 	ElMessage.success('消息发送成功')
			// }
			ElMessage.success('消息发送成功')
			registerSuccess.value = false
		} catch (error) {
			ElMessage.error('消息发送失败')
		} finally {
			sendingMessage.value = false
		}
	}

	/**
	 * 跳转到登录页面
	 */
	const goToLogin = () => {
		router.push('/login')
	}
</script>

<style scoped>
	.register-container {
		position: relative;
		min-height: 100vh;
		padding: 20px;
		background: #f5f7fa !important;
	}

	/* 确保表单可见性 */
	.el-form {
		opacity: 1 !important;
		visibility: visible !important;
		transform: none !important;
	}

	/* 强制显示输入框 */
	:deep(.el-input) {
		--el-input-border-color: #d6e4e3;
		--el-input-hover-border-color: #1a4746;
		--el-input-focus-border-color: #1a4746;
	}

	/* 背景与布局调整 */
	.register-container {
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: linear-gradient(135deg, #F9FBF8 0%, #EFF3F2 100%);
		padding: 24px;
	}

	/* 表单容器调整 */
	.el-form {
		width: 100%;
		max-width: 400px;
		background: white;
		border-radius: 12px;
		padding: 40px 32px;
		box-shadow: 0 8px 24px rgba(26, 71, 70, 0.08);
	}

	/* 输入框深度样式 */
	:deep(.el-input__wrapper) {
		border-radius: 8px !important;
		box-shadow: 0 0 0 1px var(--el-input-border-color) !important;
		transition: all 0.3s !important;
		height: 44px !important;
	}

	:deep(.el-input__wrapper:hover),
	:deep(.el-input__wrapper.is-focus) {
		box-shadow: 0 0 0 2px #1A4746 !important;
	}

	:deep(.el-input__inner)::placeholder {
		color: #9DBFBD !important;
		font-size: 14px;
	}

	/* 选择框样式 */
	.custom-select {
		width: 100%;
	}

	:deep(.el-select .el-input__wrapper) {
		box-shadow: 0 0 0 1px var(--el-input-border-color) !important;
	}

	:deep(.el-select .el-input__wrapper:hover),
	:deep(.el-select .el-input__wrapper.is-focus) {
		box-shadow: 0 0 0 2px #1A4746 !important;
	}

	/* 图标颜色适配 */
	.input-icon :deep(svg) {
		color: #6a9e9c !important;
		width: 1.2em !important;
		height: 1.2em !important;
	}

	/* 密码眼睛图标 */
	.eye-icon :deep(svg) {
		color: #6A9E9C !important;
		transition: color 0.3s;
	}

	.eye-icon:hover :deep(svg) {
		color: #1A4746 !important;
	}

	/*错误提示对齐图片样式 */
	:deep(.el-form-item__error) {
		padding-left: 24px;
		color: #d32f2f !important;
		font-size: 12px;
		background: url('data:image/svg+xml;utf8,<svg viewBox="0 0 1024 1024" xmlns="http://.w3.org/2000/svg"><path fill="%23d32f2f" d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896zm0 192a48 48 0 0 0-48 48v272a48 48 0 0 0 96 0V304a48 48 0 0 0-48-48zm0 384a48 48 0 1 0 0-96 48 48 0 0 0 0 96z"/></svg>') no-repeat left center/12px;
	}

	/* 注册按钮优化 */
	.register-btn {
		width: 100%;
		height: 48px;
		background: linear-gradient(135deg, #1A4746 0%, #2D6D6B 100%) !important;
		border: none !important;
		border-radius: 8px;
		color: white !important;
		font-size: 16px !important;
		letter-spacing: 2px;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
		margin-top: 10px;
	}

	.register-btn:hover:not(.is-disabled) {
		transform: translateY(-2px);
		box-shadow: 0 8px 16px rgba(26, 71, 70, 0.2) !important;
	}

	.register-btn.is-disabled {
		background: #C3D8D7 !important;
	}

	/* 注册成功后的操作区域 */
	.success-actions {
		margin-top: 20px;
		display: flex;
		flex-direction: column;
		gap: 12px;
	}

	.send-message-btn {
		width: 100%;
		background: linear-gradient(135deg, #4CAF50 0%, #81C784 100%) !important;
		border: none !important;
		color: white !important;
	}

	.send-message-btn:hover {
		opacity: 0.9;
	}

	.go-login-btn {
		width: 100%;
	}
</style>